package com.kangyi.app.controller;

import com.kangyi.app.service.FavoriteService;
import com.kangyi.dto.ToggleFavoriteDTO;
import com.kangyi.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Blank
 * @version 1.0
 */
@RestController
@RequestMapping("/app/")
@Api(tags = "收藏相关接口")
@Slf4j
public class FavoriteController {

    @Autowired
    private FavoriteService favoriteService;

    @PostMapping("/toggleFavorite")
    @ApiOperation("收藏/取消收藏养老院")
    public Result toggleFavorite(ToggleFavoriteDTO toggleFavoriteDTO){
        log.info("收藏/取消收藏养老院:{}", toggleFavoriteDTO);
        // 输入验证
        if (toggleFavoriteDTO == null || toggleFavoriteDTO.getAction() == null) {
            return Result.error("输入参数不能为空");
        }
        try {
            handleToggleFavorite(toggleFavoriteDTO);
            return getSuccessResult(toggleFavoriteDTO.getAction());
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            // 记录异常日志
            log.error("处理收藏/取消收藏操作时发生错误", e);
            return Result.error("处理收藏/取消收藏操作时发生未知错误");
        }
    }
    private void handleToggleFavorite(ToggleFavoriteDTO toggleFavoriteDTO) {
        String action = toggleFavoriteDTO.getAction();
        switch (action) {
            case "add":
                favoriteService.add(toggleFavoriteDTO);
                break;
            case "remove":
                favoriteService.remove(toggleFavoriteDTO);
                break;
            default:
                throw new IllegalArgumentException("无效的操作类型: " + action);
        }
    }
    private Result getSuccessResult(String action) {
        String message = "add".equals(action) ? "收藏成功！" : "取消收藏成功！";
        return Result.success(message);
    }
}
